<?php
/**
 * 用户逻辑层
 *
 */

namespace App\Biz;

use App\Utils\Ip;
use App\Utils\Password;
use Phper666\JWTAuth\Exception\TokenValidException;
use App\Utils\Log;

class AdminUser extends Base
{
    /****
     * 登录逻辑
     * @param array $data
     * @param $jwt
     * @return array
     */
    public static function login(array $data, $jwt, array $ipHandel)
    {
        //1.查询用户数据
        $admin = \App\Dao\AdminUser::getAdminDetailByName($data['account'],['role','detail']);
        if (!$admin) {
            throw new TokenValidException('账号不存在', 200);
        }
        //2.校验密码
        $password = Password::sign($data['password'], $admin->ec_salt);
        Log::getInstance()->info('加密后：用户密码', ['origin_password' => $data['password'], 'salt' => $admin->ec_salt, 'password' => $password]);
        if ($admin->password !== $password) {
            throw new TokenValidException('密码错误', 200);
        }
        //3.生成Token
        $token = $jwt->getToken([
            'uid'       => $admin->user_id,
            'user_name' => $admin->user_name
        ]);
        //4.修改用户最后一次登录的IP
        $ip = new Ip();
        \App\Dao\AdminUser::updateUsers(
            ['user_id' => $admin->user_id],
            ['last_ip' => $ip->ip($ipHandel), 'last_login' => time()]
        );
        return [
            'token'  => $token,
            'exp'    => $jwt->getTTL(),
            'detail' => $admin->detail,
            'menu'   => AdminRole::getUserRole($admin->role->menu_list, $admin->role->action_list) //用户拥有的菜单和权限
        ];
    }

    /**
     * 获取详情
     * @param array $data
     * @param $jwt
     */
    public static function detail(array $user)
    {
        $detail       = \App\Dao\AdminUser::getAdminDetailById($user['uid'],['role','detail']);
        $data         = $detail->toArray();
        $data['menu'] = AdminRole::getUserRole($data['role']['menu_list'], $data['role']['action_list']); //用户拥有的菜单和权限
        return $data;
    }

    /**
     * 修改密码
     * @param array $user
     * @param array $data
     * @return array
     */
    public static function updatePassword(array $user, array $data)
    {
        //1.查询用户数据
        $admin = \App\Dao\AdminUser::getAdminDetailById($user['uid']);
        if (!$admin) {
            throw new TokenValidException('账号不存在', 200);
        }
        //2.校验密码
        $password = Password::sign($data['rpassword'], $admin->ec_salt);
        Log::getInstance()->info('加密后：用户密码', ['a' => $data['rpassword'], 'b' => $admin->ec_salt, 'c' => $password]);
        if ($admin->password !== $password) {
            throw new TokenValidException('原密码错误', 200);
        }
        $handle = \App\Dao\AdminUser::updateUsers(
            ['user_id' => $admin->user_id],
            ['password' => Password::sign($data['npassword'], $admin->ec_salt)]
        );
        if(!$handle){
            throw new TokenValidException('修改失败', 200);
        }
        return [];
    }
}